package service;

import com.shfl.controller.ConvertImageContorller;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import stock.Stock;
import sun.misc.BASE64Encoder;
import util.AuthService;
import util.Check;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.filechooser.FileSystemView;

public class  RectD extends JFrame{

    private static final long serialVersionUID = 1L;

    private static RectD ed = new RectD();

    public static RectD getInstance(){
        ed = new RectD();
        return ed;
    }

    int orgx,orgy,endx,endy;
    Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
    BufferedImage image;
    BufferedImage tempImage;
    BufferedImage saveImage;
    Graphics g;


    private String results;

    private Integer resultsCount;


    public Integer getResultsCount() {
        return resultsCount;
    }

    public void setResultsCount(Integer resultsCount) {
        this.resultsCount = resultsCount;
    }

    public String getResults() {
        return results;
    }

    public void setResults(String results) {
        this.results = results;
    }

    @Override
    public void paint(Graphics g) {
        //缩放因子和偏移量
        RescaleOp ro=new RescaleOp(0.8f, 0, null);
        tempImage=ro.filter(image, null);
        g.drawImage(tempImage, 0, 0,this);
    }

    private RectD (){
        resultsCount = 0;
        snapshot();
        setVisible(true);
        setDefaultLookAndFeelDecorated(false);
        //setSize(d);//最大化窗口
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                orgx=e.getX();
                orgy=e.getY();
            }
        });
        //鼠标运动监听器
        this.addMouseMotionListener(new MouseMotionAdapter() {
            //鼠标拖拽事件
            public void mouseDragged(MouseEvent e) {
                endx=e.getX();
                endy=e.getY();
                g=getGraphics();
                g.drawImage(tempImage, 0, 0, RectD.this);
                int x=Math.min(orgx, endx);
                int y=Math.min(orgy,endy);
                //加上1，防止width,height为0
                int width=Math.abs(endx-orgx)+1;
                int height=Math.abs(endy-orgy)+1;
                g.setColor(Color.BLUE);
                g.drawRect(x-1, y-1, width+1, height+1);
                //减1，加1都是为了防止图片将矩形框覆盖掉
                saveImage=image.getSubimage(x, y, width, height);
                g.drawImage(saveImage, x, y,RectD.this);
            }
        });


        this.addKeyListener(new KeyAdapter() {
            @Override
            //按键释放
            public void keyReleased(KeyEvent e){

                //按Esc键退出
                if(e.getKeyCode()==27 || e.getKeyCode() ==10){
                    //saveToFile();
                  //  getImageStr();
                  //  setVisible(false);
                    String param = "image=" + getImageStr();
                    try {
                        dispose();
                       // ConvertImageContorller ConvertImageContorller = new ConvertImageContorller();
                      //  ConvertImageContorller.setCaptureConversion(Check.post(param));
                        ed.results = Check.post(param);
                        synchronized(Stock.obj){
                            Stock.obj.notify();
                        }

                       // setResults(Check.post(param));
                        //System.out.print(Check.post(param));
                    } catch (URISyntaxException e1) {
                         throw new RuntimeException(e1.getMessage());
                    } catch (IOException e1) {
                        throw new RuntimeException(e1.getMessage());
                    }finally {
                        dispose();
                        try{

                            System.out.print("======");
                        }catch (Exception el){
                            el.printStackTrace();
                        }
                    }
                  //  hide();


                }
            }
        });
    }
    public void saveToFile(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyymmddHHmmss");
        String name=sdf.format(new Date());
        File path=FileSystemView.getFileSystemView().getHomeDirectory();
        String format="jpg";
        System.out.print(path+File.separator+name+"."+format);
        File f=new File(path+File.separator+name+"."+format);
        try {
            ImageIO.write(saveImage, format, f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getImageStr(){
        InputStream in;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        byte[] data = null;
        // 读取图片字节数组
        try {
            ImageIO.write(saveImage, "png", baos);
            //in = new FileInputStream("");
            data = baos.toByteArray();
//            in.read(data);
//            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        System.out.print(URLEncoder.encode(encoder.encode(data)));
        // 返回Base64编码过再URLEncode的字节数组字符串
        return URLEncoder.encode(encoder.encode(data));
    }

    public void snapshot(){

        try {
            Robot robot= new Robot();
            Dimension d=Toolkit.getDefaultToolkit().getScreenSize();
            image=robot.createScreenCapture(new Rectangle(0,0,d.width,d.height));

        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //全屏运行
        RectD rd = new RectD();
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice();
        gd.setFullScreenWindow(rd);
        rd.getDefaultCloseOperation();

    }

}
class runnAble1 implements Runnable{
    @Override
    public void run() {
        RectD rd = RectD.getInstance();
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice();
        gd.setFullScreenWindow(rd);
        rd.getDefaultCloseOperation();
    }


}

class Test{

    public static void main(String[] args) {
      new Thread(new runnAble1()).start();

    }
}
